﻿using API_Service.DBHelper;
using Dapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace API_Service.BizLogic.BasicData
{
    public class KPNPrefixCfgService: BaseLogicService
    {
        public KPNPrefixCfgService(){ }
        public ExecutionResult<dynamic> QueryKPNPreFixCfgData(string vKPNPrefix = null, string vCustCode = null)
        {
            var result = new ExecutionResult<dynamic>();
            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    string sql = @"SELECT [id],[kpn_prefix],[cust_code],[remarks],[is_valid],[create_time],[create_user],[update_time],[update_user]
                                              FROM [dbo].[c_kpn_prefix_cfg_t]
                                              WHERE [is_valid]=@is_valid";
                    if (!string.IsNullOrEmpty(vCustCode))
                    {
                        sql = sql + " AND [cust_code] = @cust_code ";
                    }
                    if (!string.IsNullOrEmpty(vKPNPrefix))
                    {
                        sql = sql + " AND  [kpn_prefix] = @kpn_prefix";
                    }

                    result.Datas = conn.Query<dynamic>(sql, new { kpn_prefix = vKPNPrefix, cust_code = vCustCode, is_valid = "Y" }).ToArray();

                    Logger.WriteDebug(MethodBase.GetCurrentMethod().Name + ": " + result.Message.ToString());
                }
                catch (Exception ex)
                {
                    result.Status = false;
                    result.Message = "查询料头信息异常";
                    Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return result;
        }
        public ExecutionResult<dynamic> AddKPNPrefix(dynamic vModel)
        {
            var result = new ExecutionResult<dynamic>();
            dynamic vm = JsonConvert.DeserializeObject<dynamic>(vModel);
            if (vm != null)
            {
                //check KPN prefix exists or not 
                result = this.QueryKPNPreFixCfgData((string)vm.kpn_prefix, (string)vm.cust_code);
                if(result.Status && result.Datas.Length > 0)
                {
                    result.Status = true;
                    result.Message = "料头信息已经存在，无需重复添加";
                }
                else
                {
                    result = this.InsertKPNFreFixData(vm);
                }

            }
            else
            {
                result.Status = false;
                result.Message = "传递参数错误。";
            }
            return result;
        }
        public ExecutionResult<dynamic> UpdateKPNPrefix(dynamic vModel)
        {
            var result = new ExecutionResult<dynamic>();
            dynamic vm = JsonConvert.DeserializeObject<dynamic>(vModel);
            if (vm != null)
            {
                result = this.UpdateKPNPreFixData(vm);
            }
            else
            {
                result.Status = false;
                result.Message = "传递参数错误。";
            }
            return result;            
        }
        public ExecutionResult<dynamic> DeleteKPNPrefix(int vId)
        {
            return this.DeleteKPNPreFixData(vId);
        }
        public List<string> GetKPNPreFixString(string vCust_Code = null)
        {
            List<string> _lstKPNPrefix = new List<string>();           
            var exeResult = new ExecutionResult<dynamic>();
            exeResult = this.QueryKPNPreFixCfgData(null, vCust_Code);
            if (exeResult.Status)
            {
                try
                {
                    foreach (var item in exeResult.Datas)
                    {
                        if (!String.IsNullOrEmpty(item.kpn_prefix))
                            _lstKPNPrefix.Add(item.kpn_prefix);
                        //result = result + (string.IsNullOrEmpty((string)item.kpn_prefix) ? "" : (string)item.kpn_prefix);
                        //if (!string.IsNullOrEmpty(sbResult))
                        //{
                        //    sbResult = sbResult + ",";
                        //}
                    }
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }

            return _lstKPNPrefix;
        }
        private ExecutionResult<dynamic> InsertKPNFreFixData(dynamic vKPNPrefix)
        {
            var result = new ExecutionResult<dynamic>();
            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    string _insertSql = @"	INSERT INTO [dbo].[c_kpn_prefix_cfg_t]([kpn_prefix],[cust_code],[remarks]
                                                               ,[is_valid],[create_time],[create_user])
                                                         VALUES (@kpn_prefix,@cust_code,@remarks,@is_valid,GETDATE(),@create_user)";
                    var dbParams = new DynamicParameters();
                    dbParams.Add("@kpn_prefix",(string)vKPNPrefix.kpn_prefix, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@cust_code", (string)vKPNPrefix.cust_code, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@remarks", (string)vKPNPrefix.remarks, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@is_valid", "Y", DbType.String, ParameterDirection.Input);
                    dbParams.Add("@create_user", (string)vKPNPrefix.create_user, DbType.String, ParameterDirection.Input);

                    result.ExecuteCount = conn.Execute(_insertSql, dbParams);
                    if (result.ExecuteCount > 0)
                    {
                        result.Status = true;
                        result.Message = "新增站点捡料信息成功.";
                    }
                    else
                    {
                        result.Status = false;
                        result.Message = "新增站点捡料信息失败";
                    }
                    Logger.WriteDebug(MethodBase.GetCurrentMethod().Name + ": " + result.Message.ToString());
                }
                catch (Exception ex)
                {
                    result.Status = false;
                    result.Message = "新增站点捡料信息异常";
                    Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return result;
        }
        private ExecutionResult<dynamic> UpdateKPNPreFixData(dynamic vKPNPrefix)
        {
            var result = new ExecutionResult<dynamic>();
            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    string _insertSql = @"UPDATE[dbo].[c_kpn_prefix_cfg_t]
                                                   SET[kpn_prefix] = @kpn_prefix,[cust_code] = @cust_code,[remarks] = @remarks,[is_valid] = @is_valid,
                                                            [update_time] = GETDATE(),[update_user] = @update_user
                                                WHERE[id] = @id";
                    var dbParams = new DynamicParameters();

                    dbParams.Add("@id", (Int32)vKPNPrefix.id, DbType.Int32, ParameterDirection.Input);
                    dbParams.Add("@kpn_prefix", (string)vKPNPrefix.kpn_prefix, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@cust_code", (string)vKPNPrefix.cust_code, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@remarks", (string)vKPNPrefix.remarks, DbType.String, ParameterDirection.Input);
                    dbParams.Add("@is_valid", (string)vKPNPrefix.is_valid, DbType.String, ParameterDirection.Input);                    
                    dbParams.Add("@update_user", (string)vKPNPrefix.update_user, DbType.String, ParameterDirection.Input);


                    result.ExecuteCount = conn.Execute(_insertSql, dbParams);
                    if (result.ExecuteCount > 0)
                    {
                        result.Status = true;
                        result.Message = "更新料头信息成功.";
                    }
                    else
                    {
                        result.Status = false;
                        result.Message = "更新料头信息失败";
                    }
                    Logger.WriteDebug(MethodBase.GetCurrentMethod().Name + ": " + result.Message.ToString());
                }
                catch (Exception ex)
                {
                    result.Status = false;
                    result.Message = "更新料头信息异常";
                    Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return result;
        }
        private ExecutionResult<dynamic> DeleteKPNPreFixData(int vId)
        {
            var result = new ExecutionResult<dynamic>();
            using (IDbConnection conn = SqlCreator.Create())
            {
                try
                {
                    string _insertSql = @"DELETE FROM [dbo].[c_kpn_prefix_cfg_t] WHERE [id] = @id";
                    var dbParams = new DynamicParameters();
                    dbParams.Add("@id", vId, DbType.Int32, ParameterDirection.Input);

                    result.ExecuteCount = conn.Execute(_insertSql, dbParams);
                    if (result.ExecuteCount > 0)
                    {
                        result.Status = true;
                        result.Message = "删除料头信息成功.";
                    }
                    else
                    {
                        result.Status = false;
                        result.Message = "删除料头信息失败";
                    }
                    Logger.WriteDebug(MethodBase.GetCurrentMethod().Name + ": " + result.Message.ToString());
                }
                catch (Exception ex)
                {
                    result.Status = false;
                    result.Message = "删除料头信息异常";
                    Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
                }
                finally
                {
                    conn.Close();
                }
            }
            return result;
        }

    }

    public class KPNPrefixCfg
    {
        public int Id { get; set; }
        public string KPNPrefix { get; set; }
        public string Cust_Code { get; set; }
        public string Remarks { get; set; }

        private string _isValid = "Y";
        public string Is_Valid
        {
            get { return this._isValid; }
            set { this._isValid = String.IsNullOrEmpty(value) ? this._isValid : value; }
        }
        private string _sCreateUser = "SYSTEM_JOB";
        public string Create_User
        {
            get { return this._sCreateUser; }
            set { this._sCreateUser = String.IsNullOrEmpty(value) ? this._sCreateUser : value; }
        }
        public DateTime Create_Time { get; set; }

        private string _sUpdateUser = "SYSTEM_JOB";
        public string Update_User
        {
            get { return this._sUpdateUser; }
            set { this._sUpdateUser = String.IsNullOrEmpty(value) ? this._sUpdateUser : value; }
        }
        public DateTime Update_Time { get; set; }
    }
}